from django.contrib.auth.backends import ModelBackend
import re

from users.models import User
class MyAuthenticateBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        if not request:
            try:
                user = User.objects.get(username=username, is_superuser=True)
            except Exception as e:
                return None

            if not user.check_password(password):
                return None

            return user

        else:

            try:
                if re.match(r"^[3-9]\d{9}$", username):
                    user = User.objects.get(mobile=username)
                else:
                    user = User.objects.get(username=username)

            except User.DoesNotExist:
                return None

            else:
                return user
